<?php
namespace App\Events;

use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\Models\InboxDialog;
use App\Models\Inbox;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SendMessage extends Event implements ShouldBroadcast
{
    private $content;
    
    private $send_uid;
    
    private $receipt_uid;
    
    private $type;
    
    public function __construct($content,$send_uid,$receipt_uid,$type)
    {
        $this->content = $content;
        
        $this->send_uid = $send_uid;
        
        $this->receipt_uid = $receipt_uid;

        $this->type = $type;
    }
    
    /**
     * {@inheritDoc}
     * @see \Illuminate\Contracts\Broadcasting\ShouldBroadcast::broadcastOn()
     */
    public function broadcastOn()
    {
        $inboxDialog = InboxDialog::where(['sender_uid'=>$this->send_uid,'recipient_uid'=>$this->receipt_uid])->first();
        if(isset($inboxDialog)){
            DB::beginTransaction();
            try{
                $notifyData = new Inbox();
                $notifyData->message = $this->content;
                $notifyData->dialog_id = $inboxDialog->id;
                $notifyData->user_id = $this->send_uid;
                $notifyData->receipt = $this->receipt_uid;
                $notifyData->save();
        
                $inboxDialog->incrementAdd('recipient_unread',1);
                DB::commit();
            } catch (\PDOException $e){
                DB::rollback();
                Log::error(['成功预约面试私信发送给'.$this->type.'失败'=>$e->getMessage()]);
            }
        } else {
            DB::beginTransaction();
            try {
                $inboxDialog = new InboxDialog();
                $inboxDialog->sender_uid = $this->send_uid;
                $inboxDialog->recipient_uid = $this->receipt_uid;
                $inboxDialog->recipient_unread = 1;
                $inboxDialog->save();
                $notifyData = new Inbox();
                $notifyData->message = $this->content;
                $notifyData->dialog_id = $inboxDialog->id;
                $notifyData->user_id = $this->send_uid;
                $notifyData->receipt = $this->receipt_uid;
                $notifyData->save();
        
                DB::commit();
            }catch (\PDOException $e){
                DB::rollback();
                Log::error(['成功预约面试私信发送给'.$this->type.'失败'=>$e->getMessage()]);
            }
        }
        
        return ['dialog.'.$inboxDialog->id];
    }
    
}


